package com.lwgk.encryption;

import android.util.Base64;


import com.lwgk.constant.ConstantUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
 * created by 赵航
 * 联系微信 微信号：zhao--hang--
 * on 2019/7/10
 * --------------------------------------------------------------------------
 * 描述：该类为DES加密类，其中加密的 DESKeySpec(x)
 * 注意事项： x必须为字节为8个字节的任意字符,不然加密会失败。一定必须为8个字节的字符串，加密失败会返回加密前的字段
 */
public class DesSecreat {
    private static final DesSecreat ourInstance = new DesSecreat();

    public static DesSecreat getInstance() {
        return ourInstance;
    }

    private DesSecreat() {

    }

    /**
     * 1.字符串的加密
     * 加密
     * 加密失败会返回加密前的字段
     **/
    public String encryptPassword(String clearText) {
        if (clearText == null || "".equals(clearText)) {
            return clearText;
        }
        try {
            DESKeySpec keySpec = new DESKeySpec(ConstantUtils.SAVEKEY.getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            String encrypedPwd = Base64.encodeToString(cipher.doFinal(clearText.getBytes("UTF-8")), Base64.DEFAULT);
            return encrypedPwd;
        } catch (Exception e) {
        }
        return clearText;
    }

    /**
     * 2.字符串的解密
     * 解密
     * 解密失败会返回加密后的字段
     **/
    public String decryptPassword(String encryptedPwd) {
        if (encryptedPwd == null || "".equals(encryptedPwd)) {
            return encryptedPwd;
        }
        try {
            DESKeySpec keySpec = new DESKeySpec(ConstantUtils.SAVEKEY.getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(keySpec);
            byte[] encryptedWithoutB64 = Base64.decode(encryptedPwd, Base64.DEFAULT);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] plainTextPwdBytes = cipher.doFinal(encryptedWithoutB64);
            return new String(plainTextPwdBytes);
        } catch (Exception e) {
        }
        return encryptedPwd;
    }
}
